package com.computer.network.interceptor;

import com.computer.network.constant.BaseContext;
import com.computer.network.properties.JwtProperties;
import com.computer.network.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 这里添加具体的拦截逻辑（例如token验证）
        String token = request.getHeader(jwtProperties.getUserTokenName());
        
        // 如果token为null或空，直接返回401
        if (token == null || token.trim().isEmpty()) {
            log.warn("token为空，请求被拒绝");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            log.info("jwt校验：{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            
            // 检查claims是否为null
            if (claims == null) {
                log.warn("JWT解析失败：{}", token);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            
            Long userId = Long.valueOf(claims.get("userId").toString());
            //ThreadLocal 存储用户信息
            BaseContext.setCurrentId(userId);
            // 放行
            return true;
        } catch (Exception e) {
            log.error("JWT验证失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

}


